package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.RedisConstant;
import com.itheima.dao.SetMealDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetMealService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import redis.clients.jedis.JedisPool;


import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author ：hg
 * @date ：Created in 2021-12-6 23:17
 * @description：体检套餐服务
 */
@Service(interfaceClass = SetMealService.class)
@Transactional
public class SetMealServiceImpl implements SetMealService {

    @Autowired
    private SetMealDao setMealDao;

    @Autowired
    private JedisPool jedisPool;

    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;
    @Value("${out_put_path}")
    private String outPutPath;  //从属性文件中读取生成的目录位置

    /**
     * 检查组分页查询
     *
     * @param queryPageBean
     * @return
     */
    @Override
    public PageResult pageQuery(QueryPageBean queryPageBean) {
        //获取参数
        Integer pageSize = queryPageBean.getPageSize();
        Integer currentPage = queryPageBean.getCurrentPage();
        String queryString = queryPageBean.getQueryString();
        //查询
        PageHelper.startPage(currentPage, pageSize);
        Page<Setmeal> page = setMealDao.findByCondition(queryString);
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 新增套餐信息，同时需要关联检查组
     *
     * @param setmeal
     * @param checkgroupIds
     */
    @Override
    public void add(Setmeal setmeal, Integer[] checkgroupIds) {
        setMealDao.add(setmeal);
        Integer setmealId = setmeal.getId();
        setSetmealAndCheckGroup(setmealId, checkgroupIds);
        //将图片名称保存到redis集合中
        String filename = setmeal.getImg();
        jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES, filename);

        //新增套餐需要重新生产静态页面(套餐列表页面、详情详情页面)
        generateMobileStaticHtml();
    }

    //生成静态页面
    private void generateMobileStaticHtml() {
        //在生成静态页面之前需要得到数据
        List<Setmeal> list = setMealDao.findAll();
        //生成套餐列表静态页面
        generateMobileSetmealListHtml(list);
        //生成套餐详情静态页面
        generateMobileSetmealDetailHtml(list);
    }

    //生成套餐列表静态页面
    public void generateMobileSetmealListHtml(List<Setmeal> setmealList) {
        Map<String, Object> map = new HashMap<>();
        map.put("setmealList", setmealList);
        generateHtml("mobile.setmeal.ftl", "m_setmeal.html", map);
    }

    //生成套餐详情静态页面(生成多个)
    public void generateMobileSetmealDetailHtml(List<Setmeal> setmealList) {
        for (Setmeal setmeal : setmealList) {
            Map<String, Object> map = new HashMap<>();
            map.put("setmeal", setMealDao.findById(setmeal.getId()));
            generateHtml("mobile_setmeal_detail.ftl", "setmeal_detail_" + setmeal.getId() + ".html", map);
        }
    }

    //生成套餐详情页面,通用的方法
    public void generateHtml(String templateName, String htmlPageName, Map map) {
        //获取配置对象
        Configuration configuration = freeMarkerConfigurer.getConfiguration();
        Writer out = null;
        try {
            //加载模板文件
            Template template = configuration.getTemplate(templateName);
            //生成地址名
            File fileName = new File(outPutPath + "\\" + htmlPageName);
            //构造输出流
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName)));
            //输出文件
            template.process(map, out);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                assert out != null;
                out.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }


    //绑定套餐和检查组的多对多关系
    private void setSetmealAndCheckGroup(Integer id, Integer[] checkgroupIds) {
        for (Integer checkgroupId : checkgroupIds) {
            Map<String, Integer> map = new HashMap<>();
            map.put("setmeal_id", id);
            map.put("checkgroup_id", checkgroupId);
            setMealDao.setSetmealAndCheckGroup(map);
        }

        //
    }

    /**
     * 查询所有检查套餐
     *
     * @return
     */
    @Override
    public List<Setmeal> findAll() {
        return setMealDao.findAll();
    }

    /**
     * //根据id查询套餐信息
     *
     * @param id
     * @return
     */
    @Override
    public Setmeal findById(Integer id) {
        return setMealDao.findById(id);
    }

    /**
     * 查询套餐预约占比数据
     * @return
     */
    @Override
    public List<Map<String, Object>> findSetmealCount() {


        return setMealDao.findSetmealCount();
    }

}
